using Microsoft.AspNetCore.Mvc;
using Study1.Common;
using ClassDemo.Model.DTO;
using ClassDemo.Services;
using ClassDemo.Model.VO;
using ClassDemo.Repository;
using ClassDemo.Service;
using Asp.Versioning;
using ClassDemo.Model.Entity;

namespace ClassDemo.Controllers;

/// <summary>
/// 认证控制器
/// </summary>
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/auth")]
[Produces("application/json")]
public class AuthController : ControllerBase
{
    private readonly ITeacherRepository _teacherRepository;
    private readonly IStudentService _studentService;
    private readonly IPasswordService _passwordService;
    private readonly IJwtService _jwtService;

    public AuthController(ITeacherRepository teacherRepository, IStudentService studentService, IPasswordService passwordService, IJwtService jwtService)
    {
        _teacherRepository = teacherRepository;
        _studentService = studentService;
        _passwordService = passwordService;
        _jwtService = jwtService;
    }

    /// <summary>
    /// 教师登录接口
    /// </summary>
    /// <param name="loginDto">教师登录信息，包含手机号和密码</param>
    [HttpPost("teacher/login")]
    public async Task<ActionResult<ApiResult<LoginResponseVo>>> TeacherLogin([FromBody] TeacherLoginDto loginDto)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ApiResultFactory.BadRequest("请求参数无效"));
            }

            // 根据手机号查找教师
            var teacher = await _teacherRepository.GetByMobileAsync(loginDto.Mobile);
            if (teacher == null)
            {
                return Unauthorized(ApiResultFactory.Unauthorized("手机号或密码错误"));
            }

            // 验证密码
            if (!_passwordService.VerifyPassword(loginDto.Password, teacher.Password))
            {
                return Unauthorized(ApiResultFactory.Unauthorized("手机号或密码错误"));
            }

            // 生成JWT令牌
            var token = _jwtService.GenerateToken(teacher);

            // 构建响应
            var response = new LoginResponseVo
            {
                AccessToken = token,
                TokenType = "Bearer",
                ExpiresIn = 3600, // 1小时
                User = new TeacherVo
                {
                    Id = teacher.ID,
                    Name = teacher.Name,
                    Mobile = teacher.Mobile,
                    CreateTime = teacher.CreateTime,
                    UpdateTime = teacher.UpdateTime
                }
            };

            return Ok(ApiResultFactory.Success(response, "登录成功"));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResultFactory.Fail<LoginResponseVo>($"登录失败: {ex.Message}"));
        }
    }

    /// <summary>
    /// 学生登录接口
    /// </summary>
    /// <param name="loginDto">学生登录信息，账号可以是学号或手机号，密码为必填项</param>
    [HttpPost("student/login")]
    public async Task<ActionResult<ApiResult<StudentLoginResponseVo>>> StudentLogin([FromBody] StudentLoginDto loginDto)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ApiResultFactory.BadRequest("请求参数无效"));
            }

            // 根据账号（学号或手机号）查找学生
            Student? student = null;
            
            // 先尝试按学号查找
            student = await _studentService.GetStudentByNoAsync(loginDto.Account);
            
            // 如果按学号找不到，再按手机号查找
            if (student == null)
            {
                var students = await _studentService.GetAllStudentsAsync();
                student = students.FirstOrDefault(s => s.Mobile == loginDto.Account);
            }

            if (student == null)
            {
                return Unauthorized(ApiResultFactory.Unauthorized("账号不存在"));
            }

            // 验证密码
            if (!_passwordService.VerifyPassword(loginDto.Password, student.Password))
            {
                return Unauthorized(ApiResultFactory.Unauthorized("密码错误"));
            }

            // 生成JWT令牌
            var token = _jwtService.GenerateToken(student);

            // 构建学生VO
            var studentVo = new StudentVo
            {
                Id = student.Id,
                No = student.No,
                Name = student.Name,
                Mobile = student.Mobile,
                Class = student.Class,
                Major = student.Major,
                CreateTime = student.CreateTime,
                UpdateTime = student.UpdateTime
            };

            var response = new StudentLoginResponseVo
            {
                AccessToken = token,
                TokenType = "Bearer",
                ExpiresIn = 3600, // 1小时
                User = studentVo
            };

            return Ok(ApiResultFactory.Success(response, "登录成功"));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResultFactory.Fail<StudentLoginResponseVo>($"登录失败：{ex.Message}"));
        }
    }

    /// <summary>
    /// 验证JWT令牌有效性
    /// </summary>
    /// <param name="token">需要验证的JWT令牌字符串</param>
    [HttpPost("validate")]
    public ActionResult<ApiResult<bool>> ValidateToken([FromBody] string token)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(token))
            {
                return BadRequest(ApiResultFactory.BadRequest("令牌不能为空"));
            }

            var isValid = _jwtService.ValidateToken(token);
            return Ok(ApiResultFactory.Success(isValid, "令牌验证完成"));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResultFactory.Fail<bool>($"令牌验证失败: {ex.Message}"));
        }
    }
}